<template>
    <div id="Branches">
        <el-form size="min" inline>
            <el-form-item label="输入关键字" >
                <!-- 输入框 -->
                <el-input v-model="key" :placeholder="placeholder" clearable></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary"  @click="Search">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary"  @click="Back">返回</el-button>
            </el-form-item>

        </el-form>
        <template v-if="lazy==true">
            <el-tree
                    :props="props"
                    :load="loadNode"
                    node-key="No"
                    lazy
                    :check-strictly="true"
                    :default-checked-keys="treeChecked"
                    show-checkbox
                    @node-click="handleNodeClick"
                    @check-change="handleCheckChange">
            </el-tree>
        </template>
        <template v-else>
            <el-tree
                    :props="props"
                    :data="treeData"
                     node-key="No"
                    :check-strictly="true"
                    :default-checked-keys="treeChecked"
                    show-checkbox
                    default-expand-all
                    @node-click="handleNodeClick"
                    @check-change="handleCheckChange"
                    ref="tree"
                    v-show="isShow==true"
            ></el-tree>
        </template>
        <!--Table表格-->
        <el-table :data="tableData"  border
                  :header-cell-style="{background:'#f5f7fab5',color:'#777'}"
                  @row-dblclick="RowSelect"
                  @selection-change="handleSelectionChange"
                  @current-change="currentChange"
                  ref="table"
                  v-show="isShow==false">
            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column v-for="item in tableColumnData"  :key="item.field" :label="item.text" :prop="item.field"  :width="item.width"   :show-overflow-tooltip='true'>
            </el-table-column>
        </el-table>
    </div>
</template>

<script>
    export default {
        name: "Branches",
        props:{
            mapExt:{
                type:Object
            },
            selectRow:{
                type:Array,
                default:()=>[]
            },
        },
        data(){
            return{

                params:{},//参数
                webUser:{},
                isShow:true,
                key:"",
                placeholder:"",
                props:{
                    children: "children",
                    label: "Name",
                    isLeaf: 'leaf'
                },
                lazy:false,
                treeData:[],
                treeChecked:[],
                selectType:true,//是否多选
                rootNo:"0",//根节点
                tableData:[],
                tableColumnData:[],
                childrenJSON: [],
                multipleSelection:[]


            }
        },
        created(){
            this.params = this.$store.getters.getData;
            this.webUser = this.$store.getters.getWebUser;
            this.placeholder = this.GetPara(this.mapExt.AtPara,"SearchTip");
            this.selectType = this.GetPara(this.mapExt.AtPara,"SelectType")=="0"?false:true;
            this.rootNo = this.mapExt.Doc;
            if (this.rootNo == "@WebUser.FK_Dept") {
                this.rootNo = this.webUser.FK_Dept;
            }
            if (this.rootNo == "@WebUser.OrgNo") {
                this.rootNo = this.webUser.OrgNo;
            }
            if (this.rootNo == null || this.rootNo == undefined) {
                this.rootNo = "0"
            }
            if(this.mapExt.Tag2==""){
                this.$message.error("配置错误:查询数据源，初始化树的数据源不能为空。");
                return;
            }
            this.selectRow.forEach(item=>{
                this.treeChecked.push(item.No);
            });
            this.multipleSelection=this.selectRow;
            this.$nextTick(()=>{
                this.multipleSelection.forEach(row => {
                    this.$refs.table.toggleRowSelection(row,true);
                });
            });
            let treeUrl = this.mapExt.Tag2;
            treeUrl = treeUrl.replace(/~/g,"'");
            if(treeUrl.toLowerCase() .indexOf("parentno='@key'")!=-1)
                this.lazy=true;
            if(this.lazy==false){
                let json = this.loadTreeData(this.rootNo);
                this.treeData =this.findChildren(json,this.rootNo);
            }

        },
        methods:{
            loadNode(node, resolve) {
                if (node.level === 0) {
                    return resolve(this.loadTreeData(this.rootNo));
                }
                if (node.level >= 1){
                    return resolve(this.loadTreeData(node.key));
                }
            },
            loadTreeData(parentNo){
                let treeUrl = this.mapExt.Tag2;
                treeUrl = treeUrl.replace(/@Key/g,parentNo);

                let json=null;
                //SQL查询
                if(this.mapExt.DBType==0)
                    json = this.GetDataTableByField("Tag2", parentNo);
                else
                    json = this.DBAccess.RunDBSrc(treeUrl, this.mapExt.DBType);
                //转换树形结构

                return json;
            },
            loadTableColumn(){
                let columns = this.mapExt.Tag;
                //显示列的中文名称.
                if (typeof columns == "string" && columns!="") {
                    columns.split(",").forEach(item=>{
                        let exp = item.split("=");
                        let field;
                        let title;
                        if (exp.length == 1) {
                            field = title = exp[0];
                        } else if (exp.length == 2) {
                            field = exp[0];
                            title = exp[1];
                        }
                        if (!this.isLegalName(field)) {
                            return true;
                        }
                        this.tableColumnData.push({
                            field: field,
                            text: title
                        });
                    });
                } else {
                    this.tableColumnData.push({
                        field:  'No',
                        text: '编号'
                    });
                    this.tableColumnData.push({
                        field:  'Name',
                        text: '名称'
                    });
                }
            },
            handleNodeClick(node){
                if (this.treeData[0].No == node.No) {
                    this.childrenJSON = node;
                    this.$set(this.childrenJSON, 'children', []);
                    this.childrenJSON.children=this.loadTreeData(node.No);
                }
            },
            handleCheckChange(data, checked){
                if(checked == true && this.selectType == false){
                    this.$refs.tree.setCheckedNodes([data]);
                    this.multipleSelection=[data];
                }else{
                    if(checked==true){
                        this.multipleSelection.push(data);
                    } else{
                        //需要移除
                        let idx=0;
                        this.multipleSelection.forEach(item=>{
                            if(item.No == data.No){
                                return false;
                            }
                            idx++;

                        });
                        this.multipleSelection.splice(idx,1);
                    }
                }
            },

            RowSelect(){

            },
            Search(){
                this.isShow= false;
                //根据查询显示表格
                let json;
                let dataTable = this.mapExt.Tag1
                if (this.mapExt.dbType == 0) {
                    json = this.GetDataTableByField("Tag1", this.Key);
                } else {
                    dataTable = dataTable.replace(/@Key/g,this.Key);
                    json = this.DBAccess.RunDBSrc(dataTable);
                }
                this.tableData = json;


            },
            Back(){
                this.isShow=true;
                this.treeData = this.loadTreeData(this.rootNo);
            },
            handleSelectionChange(val){
                if(this.selectType==false){
                    if (val.length > 1) {
                        this.$refs.table.clearSelection()
                        this.$refs.table.toggleRowSelection(val[val.length-1]);
                    }
                }
                this.multipleSelection=this.$refs.table.store.states.selection;


            },
            currentChange(val){
                this.$refs.table.toggleRowSelection(val);
            },
            GetDataTableByField(field,keyVal){
                let en = new this.Entity("BP.Sys.MapExt", this.mapExt);
                en.MyPK = this.mapExt.MyPK;
                let json = en.DoMethodReturnString("GetDataTableByField", field, "@Key=" + keyVal, null, this.params.WorkID);
                if (json.indexOf("err@") != -1) {
                    alert(json);
                    return "";
                }
                json = JSON.parse(json);
                return json;
            },
            isLegalName(name) {
                if (!name) {
                    return false;
                }
                return name.match(/^[a-zA-Z\$_][a-zA-Z\d\$_]*$/);
            },
            findChildren :function(jsonArray, parentNo) {
                let appendToTree = function (treeToAppend, child) {
                    treeToAppend.forEach(o=>{
                        if (o.No == child.ParentNo) {
                            o.children.push({
                                "No": child.No,
                                "Name": child.Name,
                                "children": [],
                            });
                        } else {
                            appendToTree(o.children, child);
                        }
                    });
                };

                let jsonTree = [];
                if (jsonArray instanceof Array  && typeof parentNo !== "undefined") {
                    //如果parentNo不为0，则增加parentNo的部门数据
                    if (parentNo != 0) {
                        jsonArray.forEach( item=>{
                            if (item.No == parentNo) {
                                jsonTree.push({
                                    "No": parentNo,
                                    "Name": item.Name,
                                    "children": []
                                });
                                return;
                            }
                        });
                    }
                    jsonArray.forEach( o=>{
                        if (o.ParentNo == parentNo) {
                            jsonTree.push({
                                "No": o.No,
                                "Name": o.Name,
                                "children": [],
                            });
                        } else {
                            appendToTree(jsonTree, o);
                        }
                    });
                }

                function _(treeArray) {
                    treeArray.forEach(o=>{
                        if (o.children instanceof Array) {
                            if (o.children.length == 0){
                            } else {
                                _(o.children);
                            }
                        }
                    });
                }
                _(jsonTree);
                return jsonTree;
            }

        },
        watch: {
            multipleSelection(){
                this.$emit("on-selectRow-change",this.multipleSelection);
            },

        }
    }
</script>

<style scoped>

</style>